package com.linkcld.demo.service;

import com.beyond.sso.client.validation.Assertion;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.security.bsso.authentication.BssoAssertionAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @since 2019-03-27
 */
public class SsoUserDetailService implements AuthenticationUserDetailsService<BssoAssertionAuthenticationToken> {

    private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD";
    private boolean convertToUpperCase = true;

    @Override
    public UserDetails loadUserDetails(BssoAssertionAuthenticationToken token) throws UsernameNotFoundException {

        final List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        Assertion assertion = token.getAssertion();
        Map<String, Object> attributes = assertion.getPrincipal().getAttributes();

        String userId = String.valueOf(attributes.get("ID"));

        // TODO: 2019-03-27 通过userId自行获取user并返回

        return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE,
            true, true, true, true, grantedAuthorities);
    }
}
